package com.zyy.rabbitmq.service;

import com.alibaba.fastjson2.JSON;
import com.zyy.rabbitmq.pojo.Order;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;

/**
 * @Description: 类描述
 * @Author: zyy
 * @Date: 2023/06/08 23:10
 */
@Service
public class MQOrderService {


    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private JdbcTemplate jdbcTemplate;


    @PostConstruct
    public void regCallBack() {
        rabbitTemplate.setConfirmCallback((correlationData, ack, s) -> {
            String id = correlationData.getId();
            Integer orderId = Integer.parseInt(id);
            if (ack) {
                updateOrderMessage(1, orderId);
            } else {
                updateOrderMessage(2, orderId);
            }
        });
    }

    public void updateOrderMessage(Integer status, Integer orderId) {
        //TODO 注意 失败情况，重试次数应该+1
        String sql = "update order_message set status=? where order_id=?";

        int count = jdbcTemplate.update(sql, status, orderId);
        if (count != 1) {
            //监控
        }
    }

    public void sendMessage(Order order) {
        String message = JSON.toJSONString(order);
        rabbitTemplate.convertAndSend("order.fanout.exchange", "", message, new CorrelationData(order.getOrderId() + ""));
    }
}
